<template>
    <enjoy-drawer :visible.sync="isShow" :title="headerTitle" @close="handleClose" center top="14vh" width="956px" append-to-body :fullscreen="fullscreen">
        <el-form :model="dialogForm" size="small" :inline="true" label-suffix=":" ref="detailForm" :rules="rules" label-width="100px">
            <el-row>
                <!--              大缺陷：-->
                <el-form-item :label="$t('defectIncoming.bigDefect')" prop="maxFlawName">
                    <el-autocomplete disabled style="width:100%" popper-class="my-autocomplete" v-model="dialogForm.maxFlawName" :fetch-suggestions="flawMaxRemoteMethod" placeholder="请输入内容" @select="handleFlawMaxSelect">
                        <i class="el-icon-search el-input__icon" slot="suffix">
                        </i>
                        <template slot-scope="{ item }">
                            {{ item.maxFlawName }}
                        </template>
                    </el-autocomplete>
                </el-form-item>
                <el-form-item :label="$t('defectIncoming.minFlawName')" prop="minFlawName">
                    <el-input v-model="dialogForm.minFlawName" :placeholder="$t('public.placeholder',{placeholder: $t('defectIncoming.minFlawName')})" size="small" @input="handleQuery(dialogForm.minFlawName)" />
                </el-form-item>
                <el-form-item :label="$t('basicData.MajorDefectsCode')" prop="maxFlawCode">
                    <el-input disabled v-model="dialogForm.maxFlawCode" :placeholder="$t('public.placeholder',{placeholder: $t('basicData.MajorDefectsCode')})" size="small" @keyup.enter.native="handleQuery" />
                </el-form-item>
                <!--              缺陷类型：-->
                <el-form-item :label="$t('basicData.flawType')" prop="flawType">
                    <el-select v-model="dialogForm.flawType" style="width:100%;" @change="flawTypechange" size="small" reserve-keyword :placeholder="$t('public.inputPl')+$t('basicData.flawType')">
                        <el-option v-for="item in dict.type.NYIQC_FLAW_TYPE" :key="item.value" :label="item.label" :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-row>
            <el-table stripe border :data="dialogForm.typeList" class="edit-table" max-height="425">
                <!--          序号-->
                <el-table-column :label="$t('public.serialNum')" type="index" width="55" align="center" />
                <!--          小缺陷名称-->
                <el-table-column :label="$t('defectIncoming.minFlawName')" align="left" prop="minFlawName" />
                <!--          小缺陷名称-->
                <el-table-column :label="$t('basicData.smallDefectCode')" align="left" prop="minFlawCode" />

                <!--          物料类型-->
                <!-- <el-table-column label="物料小类" align="left" prop="materialMin" /> -->
                <el-table-column :label="$t('basicData.flawType')">
                    <template slot-scope="scope">
                        <span>{{  formatNYIQC_FLAW(scope.row.flawType)}}</span>
                    </template>
                </el-table-column>

                <!--          描述-->
                <el-table-column :label="$t('basicData.description')" align="left" prop="description" />
                <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="160">
                    <template slot-scope="scope">
                        <div class="action-wrap">
                            <table-body-btn type="gwedit" @click.native="handleEdit(scope.row)" />
                            <table-body-btn type="gwdelete" @click.native="handleDelete(scope.row)" />
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" layout="total, sizes, prev, pager, next, jumper" />
        </el-form>
        <!-- 编辑小缺陷 -->
        <detail-min :visible.sync="minVisible" v-model="rowMinData" type="2" @refresh="getList()"></detail-min>
        <div slot="footer">
            <el-button @click="$emit('update:visible',false)" icon="el-icon-close" size="small">{{$t('public.close')}}</el-button>
        </div>
    </enjoy-drawer>
</template>

<script>
import {listAllFlawProjectMessage} from '@/api/basic/gaugeMessage'
import {addFlawProject, deleteMinFlaw, listAllMaxFlaw, listMinFlaw, updateFlawProject,} from '@/api/basic/flawProject'
import EnjoySelectUser from '@/components/EnjoySelectUser'
import EnjoySelectDeptTree from '@/components/EnjoySelectDeptTree'
import FileUploadInput from '@/components/FileUploadInput'
import EnjoyDrawer from '@/components/EnjoyDrawer'
import {listALLMaterialType} from '@/api/basic/materialtype'
import DetailMin from './detailMin'

export default {
    name: 'flaw-drawer',
    components: {
        EnjoySelectUser,
        EnjoySelectDeptTree,
        FileUploadInput,
        EnjoyDrawer,
        DetailMin,
    },
    dicts: [
        'NYIQC_FLAW_TYPE', //缺陷类型
    ],
    props: {
        value: {
            type: Object,
        },
        visible: {
            type: Boolean,
            default: false,
        },
        type: [String, Number], //1:新增  2：编辑 3：查看
    },
    watch: {
        visible(val) {
            if (val) {
                this.queryParams.pageSize = 10
                this.getList()
            }
        },
    },
    computed: {
        isShow: {
            get() {
                return this.visible
            },
            set() {
                this.$emit('update:visible', false)
            },
        },
        headerTitle() {
            const { type } = this
            let title = ''
            if (type == 1) {
                title = this.$t('public.add') +" "+ this.$t('basicData.smallDefect')
            }
            if (type == 3) {
                title = this.$t('basicData.smallDefect') +" "+ this.$t('public.detail')
            }

            return title
        },
    },
    data() {
        return {
            loading: false,
            fullscreen: false,
            deviceOptions: undefined,
            factoryOptions: undefined,
            minVisible: false,
            dialogForm: { typeList: [] },
            queryParams: {
                pageNum: 1,
                pageSize: 20,
                maxFlawName: '',
                maxFlawCode: '',
                flawType: '',
            },
            rowMinData: {},
            total: 0,
            // 表单校验
            rules: {},
        }
    },
    methods: {
        formatNYIQC_FLAW(e) {
            if (e) {
                let obj = this.dict.type.NYIQC_FLAW_TYPE.find((item) => {
                    return item.value === e
                })
                if (obj) {
                    return obj.label
                } else {
                    return ''
                }
            } else {
                return ''
            }
        },
        getList() {
            this.queryParams.maxFlawId = this.value.id
            listMinFlaw(this.queryParams).then((res) => {
                if (res.code == 200) {
                    this.dialogForm = { ...this.value, ...res.rows[0] }
                    this.dialogForm.typeList = res.rows
                    this.total = res.total
                }
            })
        },
        flawTypechange(e) {
            this.queryParams.flawType = e
            listMinFlaw(this.queryParams).then((res) => {
                if (res.code == 200) {
                    this.dialogForm.typeList = res.rows
                    this.total = res.total
                }
            })
        },
        handleQuery(e) {
            this.queryParams.minFlawName = e
            listMinFlaw(this.queryParams).then((res) => {
                if (res.code == 200) {
                    this.dialogForm.typeList = res.rows
                    this.total = res.total
                }
            })
        },
        /** 发起提交 */
        submitForm: function () {
            this.$refs.detailForm.validate((valid) => {
                let action = this.type == 1 ? addFlawProject : updateFlawProject
                if (valid) {
                    this.loading = true
                    action(this.dialogForm).then(
                        (res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$emit('refresh')
                                this.$modal.msgSuccess('操作成功!')
                                this.$emit('update:visible', false)
                            }
                        },
                        (err) => {
                            this.loading = false
                        }
                    )
                }
            })
        },
        handleClose(done) {
            this.$emit('update:visible', false)
            this.queryParams.pageSize = 20
        },
        //设备模糊查询
        deviceRemoteMethod(val, cb) {
            console.log(val)
            listAllFlawProjectMessage({ deviceName: val }).then((res) => {
                this.deviceOptions = res.data.map((i) => i.deviceName)
                cb(res.data)
            })
        },
        handleDeviceSelect(e) {
            this.dialogForm.deviceName = e.deviceName
            this.dialogForm.gaugeType = e.gaugeType
            this.$refs.deviceName.$emit('el.form.blur')
        },
        handleDeviceBlur(e) {
            const { deviceOptions, dialogForm } = this
            if (!deviceOptions.includes(dialogForm.deviceName)) {
                this.dialogForm.deviceName = ''
            }
        },

        handleExpireTime(e) {
            console.log(e)
            const today = new Date().getTime()
            const val = new Date(e).getTime()
            if (val > today) {
                this.dialogForm.remDay = ~~(
                    (val - today) /
                    1000 /
                    60 /
                    60 /
                    24
                ).toFixed(1)
            } else {
                this.dialogForm.remDay = 0
            }
            this.$forceUpdate()
        },
        materialRemoteMethod(val, cb) {
            listALLMaterialType({ typeName: val }).then((res) => {
                this.materialOptions = res.data.map((i) => i.typeName)
                cb(res.data)
            })
        },
        handleMaterialSelect(e) {
            this.dialogForm.materialMiddle = e.materialMiddle
            this.$refs.materialMiddle.$emit('el.form.blur')
        },
        handleMaterialBlur(e) {
            const { materialOptions, dialogForm } = this
            if (!materialOptions.includes(dialogForm.materialMiddle)) {
                this.dialogForm.materialMiddle = ''
            }
        },
        flawMaxRemoteMethod(val, cb) {
            listAllMaxFlaw({ maxFlawName: val }).then((res) => {
                this.materialOptions = res.data.map((i) => i.typeName)
                cb(res.data)
            })
        },
        handleFlawMaxBlur(e) {
            this.dialogForm.materialMiddle = e.materialMiddle
            this.$refs.materialMiddle.$emit('el.form.blur')
        },
        handleFlawMaxSelect(e) {
            const { materialOptions, dialogForm } = this
            this.dialogForm.maxFlawId = e.maxFlawId
            if (!materialOptions.includes(dialogForm.maxFlawName)) {
                this.dialogForm.maxFlawName = ''
            }
        },
        handleAdd() {
            this.dialogForm.typeList.push({})
        },
        handleFlawTypeChange() {},
        /** 编辑小缺陷按钮操作 */
        handleEdit(row) {
            this.rowMinData = Object.assign({}, { ...this.value }, { ...row })
            this.minVisible = true
        },
        /** 删除小缺陷按钮操作 */
        handleDelete(row) {
            const dictIds = row && row.id
            const projectNames = (row && row.projectName) || this.names
            this.$modal
                .confirm(
                    '是否确认删除小缺陷名称为"' +
                        row.minFlawName +
                        '"的数据项？'
                )
                .then(function () {
                    return deleteMinFlaw(dictIds)
                })
                .then(() => {
                    this.getList()
                    this.$modal.msgSuccess(this.$t('processDefinition.successfullyDeleted'))
                })
                .catch(() => {})
        },
    },
}
</script>

<style scoped>
.table-add {
    text-align: center;
    font-size: 12px;
    color: #666;
    padding: 7px;
    border: 1px solid #e3e8ee;
    border-top: 0;
    cursor: pointer;
}
.table-add:hover {
    color: #004d8c;
}
.edit-table ::v-deep .el-form-item--small.el-form-item {
    margin-bottom: 0;
}
</style>
